<?php

include_once 'Super_Model.php';

class Application_Model_Pages extends Super_Model {

    public function getPage($page_name) {
        $sql = 'SELECT * FROM `pages` Where `url` = \'' . addslashes(trim($page_name)) . '\'';
        $result = $this->getRow($sql);
        if ($result) {
            $result['alike'] = $this->getAlikePage($result['id']);
            return $result;
        }
        return 0;
    }

    protected function getAlikePage($page_id, $limit=5) { // похожие статьи
        $LBLM = new Admin_Model_Labels();
        $page_tags = $LBLM->getLabelsByPage($page_id);
        if ($page_tags) {
            $sql = 'SELECT `title`, `url`, `category_id` FROM `pages` p WHERE p.`id` != '.(int)$page_id.' AND p.id IN (
                        SELECT `obj_id` FROM `attach` WHERE `obj_type` = \'page\' AND `target_type` = \'label\'
                        AND `target_id` IN ('.  implode(',', $page_tags).'))
                        ORDER BY RAND()
                    LIMIT '.(int)$limit;
            $tags = $this->getAll($sql);
            return $tags;
        }
        return array();
    }

    public function getPageByID($page_id) {
        $sql = 'SELECT * FROM `pages` Where `id` = \'' . intval($page_id) . '\'';
        $result = $this->getRow($sql);
        if ($result) {
            return $result;
        }
        return 0;
    }

    public function getPageUrl($page_id) {
        $page = $this->getPageByID($page_id);
        if ($page) {
            $CTM = new Application_Model_CatsAndTags();
            $cat = $CTM->getCategoryByID($page['category_id']);
            if ($cat) {
                return '/' . $cat['url'] . '/' . $page['url'];
            }
        }
        return '';
    }

    public function getPageQs($page_id) {
        $sql = 'SELECT `qs` FROM `pages` Where `id` = ' . (int) $page_id;
        $result = $this->GetOne($sql);
        if ($result) {
            return $result;
        }
        return '';
    }

    public function getCntCommentPage() {
        $sql = 'SELECT `page_id`, count(`id`) as cnt_comments FROM `comments`Group By `page_id`';
        $result = $this->getAssoc($sql);
        if ($result) {
            return $result;
        }
        return 0;
    }

    public function incViewPage($page_id, $cnt_view) {
        if (!empty($page_id) && !empty($cnt_view)) {
            $sql = "UPDATE `pages` SET
                       `view` = " . (int) $cnt_view . "
                    WHERE `id` = " . (int) $page_id
            ;
            return $this->Exec($sql);
        }
        return false;
    }

    public function getPageQsArray($qs_str, $limit) {
        if (!empty($qs_str)) {
            $qs_array = explode('#', $qs_str);
            if (is_array($qs_array) && count($qs_array)) {
                shuffle($qs_array);
                return array_slice((array) $qs_array, 0, $limit);
            }
        }
        return array();
    }

    public function writePageQs($new_qs, $page_id) {
        $new_qs = rawurldecode($new_qs);
        if (!empty($page_id) && !empty($new_qs) && ( (strpos($new_qs, 'text=') !== false || strpos($new_qs, '&q=') !== false) )) {
            $curent_qs = $this->getPageQs($page_id);
            $curent_ar_qs = array();
            if (!empty($curent_qs)) {
                $curent_ar_qs = explode('#', $curent_qs);
            }
            if (strpos($new_qs, 'text=') !== false) {
                $pst = strpos($new_qs, 'text=');
                $new_qs = substr($new_qs, $pst + 5, strlen($new_qs));
                if (strpos($new_qs, '&') != false)
                    $qs = substr($new_qs, 0, strpos($new_qs, '&'));
            }
            if (strpos($new_qs, '&q=') !== false) {
                $pst = strpos($new_qs, '&q=');
                $new_qs = substr($new_qs, $pst + 3, strlen($new_qs));
                if (strpos($new_qs, '&') !== false)
                    $qs = substr($new_qs, 0, strpos($new_qs, '&'));
            }
            if (!empty($qs)) {
                $qs = str_replace('+', ' ', $qs);
                $qs = str_replace('"', '', $qs);
                //  добавляем в начало массива строку $qs
                array_unshift($curent_ar_qs, $qs);
                //  echo $qs ."3333333<br><br>";
                //  удаляем все элементы с индексом больше 10
                $new = array_slice($curent_ar_qs, 0, 100);
                //  склеиваем массив обратно в строку
                $str = implode($curent_ar_qs, '#');
                $sql = "UPDATE `pages` SET
                       `qs` = '" . addslashes($str) . "' 
                    WHERE `id` = " . (int) $page_id
                ;
                return $this->exec($sql);
            }
        }
        return false;
    }

    function getRandomAphorisms() {
        $sql = "SELECT * FROM `aphorisms`
                    ORDER BY RAND() LIMIT 1";
        return $this->getRow($sql);
    }

    function addTagsToPage(& $pages) {
        if (is_array($pages) && count($pages)) {
            foreach ($pages as & $page) {
                $sql = "SELECT `title`, `url` FROM `labels` l
                            join attach
                        on (`obj_type` = 'page' and `obj_id` =  " . $page['id'] . "  and target_type = 'label' and l.id = target_id)";
                $tags = $this->getAll($sql);
                $page['tags'] = $tags;
                $page['tags_html'] = '';
                if (is_array($tags) && count($tags)) {
                    $html = array();
                    foreach ($tags as $tag)
                        $html[] = '<a href="/' . $tag['url'] . '">' . $tag['title'] . '</a>';
                    $page['tags_html'] = ' | теги ' . implode(',&nbsp;', $html);
                }
            }
        }
        return;
    }

}